package com.yzq.service.impl;

import cn.hutool.core.util.ObjUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yzq.enums.ErrorCode;
import com.yzq.model.dto.likes.LikesRequest;
import com.yzq.model.entity.Likes;
import com.yzq.model.vo.UserVO;
import com.yzq.service.LikesService;
import com.yzq.mapper.LikesMapper;
import com.yzq.service.UserService;
import com.yzq.utils.ThrowUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
* @author yezhi
* @description 针对表【likes(点赞表)】的数据库操作Service实现
* @createDate 2025-07-07 14:27:55
*/
@Service
public class LikesServiceImpl extends ServiceImpl<LikesMapper, Likes>
    implements LikesService{
    @Resource
    private UserService userService;

    /**
     * 点赞图片
     * @param likesRequest 点赞请求
     * @param request 请求
     * @return 是否成功
     */
    @Override
    public Boolean likePicture(LikesRequest likesRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(likesRequest == null, ErrorCode.BAD_REQUEST);
        ThrowUtils.throwIf(ObjUtil.isNull(likesRequest.getPictureId()), ErrorCode.BAD_REQUEST);

        // 获取当前用户
        UserVO currentUser = userService.getCurrentUser(request);
        ThrowUtils.throwIf(currentUser == null, ErrorCode.UNAUTHORIZED);

        Likes likes = new Likes();
        likes.setPictureId(likesRequest.getPictureId());
        likes.setUserId(currentUser.getId());
        likes.setCreateTime(new Date());

        return save(likes);
    }

    /**
     *  取消点赞图片
     * @param likesRequest 点赞请求
     * @param request 请求
     * @return 是否成功
     */
    @Override
    public Boolean cancelLikePicture(LikesRequest likesRequest, HttpServletRequest  request) {
        ThrowUtils.throwIf(likesRequest == null, ErrorCode.BAD_REQUEST);
        ThrowUtils.throwIf(ObjUtil.isNull(likesRequest.getPictureId()), ErrorCode.BAD_REQUEST);

        // 获取当前用户
        UserVO currentUser = userService.getCurrentUser(request);
        ThrowUtils.throwIf(currentUser == null, ErrorCode.UNAUTHORIZED);

        ThrowUtils.throwIf(ObjUtil.isNull(currentUser.getId()), ErrorCode.BAD_REQUEST);
        QueryWrapper<Likes> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("picture_id", likesRequest.getPictureId())
                    .eq("user_id", currentUser.getId());
        ThrowUtils.throwIf(count(queryWrapper) == 0, ErrorCode.NOT_FOUND);
        return remove(queryWrapper);
    }

    /**
     * 判断当前用户是否点赞
     * @param likeQueryWrapper 查询条件
     * @return 是否点赞
     */
    @Override
    public Boolean isLike(QueryWrapper<Likes> likeQueryWrapper) {
        return count(likeQueryWrapper) > 0;
    }
}




